﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;

namespace PDFWriter
{
    class PDFResource : INode
    {

        public const string RESOURCE_TAG = "Resource";
        public const string OBJECT_ID = "id";
        public const string GENERATION_ID = "GenID";
        public string ReferenceID
        {
            get;
            set;
        }        
        private string xmlString = "<Resource id=\"3\">"+          
          "<Dictionary>"+
             "<DictionaryElement type=\"name\" value=\"ProcSet\">"+
               "<Array>"+
                 "<ArrayElement>/PDF</ArrayElement>"+
                 "<ArrayElement>/Text</ArrayElement>"+
               "</Array>"+
             "</DictionaryElement>"+
             "<DictionaryElement type=\"name\" value=\"Font\">"+
               "<Dictionary>"+
                 "<DictionaryElement type=\"name\" value=\"F1\"><ObjRef>4</ObjRef> </DictionaryElement>"+
               "</Dictionary>"+
             "</DictionaryElement>   "+
           "</Dictionary>"+
        "</Resource>";

        private XmlDocument reader = new XmlDocument();

        public PDFResource(string xmlString)
        {
            this.xmlString = xmlString;
            reader.LoadXml(xmlString);
        }

        public PDFResource()
        {
            reader.LoadXml(xmlString);
        }

        private string ProcesXML()
        {
            string result = null;
            string generationID = null;
            if (reader.FirstChild.Name == RESOURCE_TAG)
            {
                result = Utility.GetPDFString(reader.FirstChild.InnerXml);
                if (reader.FirstChild.Attributes[OBJECT_ID] != null)
                {
                    generationID= reader.FirstChild.Attributes[OBJECT_ID].Value;
                    if (reader.FirstChild.Attributes[GENERATION_ID] != null)
                    {
                        generationID += reader.FirstChild.Attributes[GENERATION_ID].Value;
                    }
                    else
                    {
                        generationID += " 0";
                    }                    
                    
                }
                ReferenceID = generationID + " R";

                result = generationID + " obj\n" + result + "endobj";
            }
            return result;
        }

        

        public PDFObject GetPDFObject()
        {
            return new PDFObject() { Text = ProcesXML(), ObjectType = "Resources",ObjectID = ReferenceID };
        }

        public List<PDFObject> GetPDFObjects()
        {
            return new List<PDFObject> { new PDFObject() { Text = ProcesXML() } };
        }
    }
}
